/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.servicecomb.exception;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.google.common.base.Strings;
import com.je.common.base.result.BaseRespResult;
import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.swagger.invocation.Response;
import org.apache.servicecomb.swagger.invocation.SwaggerInvocation;
import org.apache.servicecomb.swagger.invocation.exception.ExceptionToProducerResponseConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.BadSqlGrammarException;

/**
 * 执行sql异常
 *
 * @program: jecloud-workflow
 * @author:
 * @create:
 * @description:
 */
public class CloudExecuteSqlExceptionToProducerResponseConverter implements ExceptionToProducerResponseConverter<BadSqlGrammarException> {

    private static final Logger logger = LoggerFactory.getLogger(CloudExecuteSqlExceptionToProducerResponseConverter.class);

    /**
     * 异常处理顺序
     */
    private static final int ORDER = 0;

    @Override
    public Class<BadSqlGrammarException> getExceptionClass() {
        return BadSqlGrammarException.class;
    }

    @Override
    public Response convert(SwaggerInvocation swaggerInvocation, BadSqlGrammarException e) {
        logger.error(ExceptionUtil.getMessage(e));
        String url = ((Invocation) swaggerInvocation).getRequestEx().getRequestURI();
        logger.info("throw APIWarnException error...........url....." + url);
        logger.info("throw APIWarnException error...........context....." + ((Invocation) swaggerInvocation).getContext().toString());
        String[] message = buildExecutionInfo(e.getMessage());
        BaseRespResult baseRespResult;
        if (Strings.isNullOrEmpty(message[1])) {
            baseRespResult = BaseRespResult.errorResult("9999", null, "执行sql异常 \n ");
        } else {
            baseRespResult = BaseRespResult.errorResult("9999", null, "执行sql异常 \n 异常sql：" + message[0]);
        }
        logger.error("log.isErrorEnabled():{}", logger.isErrorEnabled());
        logger.info("log.isInfoEnabled():{}", logger.isInfoEnabled());
        e.printStackTrace();
        CloudExceptionInfoStorage.saveExceptionLog(url, ((Invocation) swaggerInvocation).getRequestEx().getParameterMap(), baseRespResult.getMessage(), baseRespResult.getCode(), e.getStackTrace());
        return Response.succResp(baseRespResult);
    }

    @Override
    public int getOrder() {
        return ORDER;
    }


    public String[] buildExecutionInfo(String message) {
        String[] res = new String[2];
        String[] messageArray = message.split("###");
        if (messageArray.length > 6) {
            res[0] = messageArray[5];
            res[1] = messageArray[6];
        } else {
            res[0] = message;
        }
        return res;
    }

}
